package com.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.mapper.AddressMapper;
import com.shop.pojo.Address;
import com.shop.service.AddressService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Override
    public Address findAddressName(String addressname) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("address_name",addressname);
        return addressMapper.selectOne(queryWrapper);
    }

    @Override
    public void add(Address address) {
        addressMapper.insert(address);
    }

    @Override
    public Page<Address> pageQuery(Integer pagenum, Integer pageSize, String pageQuery) {
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        Page<Address> page = new Page<>(pagenum,pageSize);
        if (pageQuery!=null&&pageQuery.length()>0){
            wrapper.like("address_id",pageQuery);
            page = addressMapper.selectPage(page,wrapper);
            List<Address> addressList = page.getRecords();
            for (Address address:
                 addressList) {
                String userName = addressMapper.findUserNameByAddressId(address.getId());
                address.setUserName(userName);
            }
            page.setRecords(addressList);
        }else{
            page = addressMapper.selectPage(page,null);
            List<Address> addressList = page.getRecords();
            for (Address address:
                    addressList) {
                String userName = addressMapper.findUserNameByAddressId(address.getId());
                address.setUserName(userName);
            }
            page.setRecords(addressList);
        }
        return page;
    }


    @Override
    public void deleteById(Integer id) {
        long count = addressMapper.findCountByAddressId(id);
        if (count>0){
            new RuntimeException();
        }
        addressMapper.deleteById(id);
    }

    @Override
    public void edit(Address address) {
        addressMapper.updateById(address);
    }

    @Override
    public Address findById(Integer id) {
        return addressMapper.selectById(id);
    }


    @Override
    public List<Address> findAll(Integer uid) {
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",uid);
        List<Address> list = addressMapper.selectList(wrapper);
        return list;
    }

    @Override
    public void delete(Integer id) {
        addressMapper.deleteById(id);
    }

}
